﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace DjangoRESTFrameworkDAL
{
    public class RestHttpClient : HttpClient
    {
        /// <summary>
        /// 获取实例
        /// </summary>
        public static RestHttpClient Instance { get; } = null;

        /// <summary>
        /// 静态构造函数
        /// </summary>
        static RestHttpClient()
        {
            Instance = new RestHttpClient();
        }
        
        /// <summary>
        /// 构造函数
        /// </summary>
        private RestHttpClient():base()
        {
            this.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            this.BaseAddress = new Uri("http://127.0.0.1:8000/");
        }
        

        public async Task<HttpResponseMessage> GetWithPolicyAsync(string url)
        {
            return await PolicyFactory.CreateCommonPolicyWrap()
                .ExecuteAsync(() => this.GetAsync(url));
        }

        public async Task<HttpResponseMessage> PostWithPolicyAsync(string url, HttpContent content)
        {
            return await PolicyFactory.CreateCommonPolicyWrap()
                .ExecuteAsync(() => this.PostAsync(url, content));
        }

        public async Task<HttpResponseMessage> DeleteWithPolicyAsync(string url)
        {
            return await PolicyFactory.CreateCommonPolicyWrap()
                .ExecuteAsync(() => this.DeleteAsync(url));
        }

        public async Task<HttpResponseMessage> PatchWithPolicyAsync(string url, HttpContent content)
        {
            var patchMethod = new HttpMethod("PATCH");
            var request = new HttpRequestMessage(patchMethod, url)
            {
                Content = content
            };
            return await PolicyFactory.CreateCommonPolicyWrap()
                .ExecuteAsync(() => this.SendAsync(request));
        }

    }
}
